<template>
	<div>
		<div class="wrap">
			<img :src="src" id="img" alt="cover" ref="myImg">
			<div class="zone" v-for="(zone, index) in zones" :key="index" :style="{
			  width: getZoneStyle(zone.width),
			  height: getZoneStyle(zone.height),
			  top: getZoneStyle(zone.top),
			  left: getZoneStyle(zone.left),
			  border: getBorderStyle()
			}" @click="handleZoneClick(zone)">
			</div>
		</div>
	</div>
</template>

<script>
	var _ = require('lodash');
	export default {
		name: 'hotarea',
		props: {
			"debug": {
				type: Boolean,
				default: false
			},
			"src": {
				type: String,
				default: ''
			},
			"areas": {
				type: Array,
				default: []
			}
		},
		data() {
			return {
				zones: []
			}
		},
		computed: {

		},
		methods: {
			//获取边框式
			getBorderStyle() {
				if (this.debug) {
					return `1px dashed #f70a0a`
				} else {
					return `0px`
				}
			},
			//获取热区样式
			getZoneStyle(val) {
				return `${(val || 0)}px`
			},
			//热区点击事件
			handleZoneClick(item) {
				if (item.isMinApp == 1) {
					//H5链接跳转
					uni.navigateTo({
						url: '/pages/webView/webView?url=' + encodeURIComponent(item.h5Link),
						animationType: 'fade-in'
					});
				} else if (item.isMinApp == 2) {
					// 小程序链接跳转
					uni.navigateTo({
						url: item.minAppLink,
						animationType: 'fade-in'
					});
				}
			},
			//重新生成热区坐标
			createZones(imgWidth, imgNaturalWidth) {
				let ratio = imgWidth / imgNaturalWidth;
				console.log("图片缩放比例", ratio)
				let itemArrs = this.areas == undefined ? [] : this.areas;
				itemArrs.forEach((item) => {
					let obj = item;
					obj.top = parseInt(item.top * ratio);
					obj.left = parseInt(item.left * ratio);
					obj.width = parseInt(item.width * ratio);
					obj.height = parseInt(item.height * ratio);
					this.zones.push(obj);
				});
				console.log(this.zones)
			}
		},
		mounted() {
			let _this = this;
			// #ifdef APP
			uni.getImageInfo({
				src: _this.src,
				success: function(res) {
					console.log("图片宽度", res.width)
					_this.createZones(_this.vuex_windowWidth, res.width);
				},
				fail: function(err) {
					console.log(err)
				}
			})
			// #endif
			// #ifndef APP
			let oImg = this.$refs.myImg;
			_this.createZones(oImg.width, oImg.naturalWidth);
			// #endif
		}
	}
</script>

<style>
	.wrap {
		position: relative;
	}

	.wrap img {
		width: 100%;
		user-select: none;
		-webkit-user-drag: none;
		-webkit-touch-callout: none;
	}

	.wrap .zone {
		position: absolute;
		cursor: pointer;

		/* border: 1px dashed #f70a0a; */
	}
</style>
